<template>
  <div>
    <el-row :gutter="15">
      <el-form ref="elForm" :model="dataForm" :rules="dataRule" size="small" label-width="100px" label-position="right"
        :disabled="setting.readonly">
        <template v-if="!loading && formOperates">
          <el-col :span="24">
            <el-form-item label-width="0">
              <JNPF-Text :style='{"width":"100%"}'
                :textStyle='{"color":"#000000","font-weight":"normal","text-decoration":"none","font-size":16,"line-height":16,"font-style":"normal","text-align":"left"}'
                value="基础信息" :closable="false">
              </JNPF-Text>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-divider content-position="center"></el-divider>
          </el-col>
          <el-col :span="24" v-if="judgeShow('picture')">
            <el-form-item label="图片:" prop="picture">
              <JNPF-UploadImg v-model="dataForm.picture" :fileSize="5" :disabled="judgeWrite('picture')" sizeUnit="MB" @change="uploadImgChange"
                :limit="5" :detailed="dataForm.picture.length == 5">
              </JNPF-UploadImg>
              <div class="img_text">图片大小不能超过5M，总数量不能超过5张（第一张为封面图）</div>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="judgeShow('title')">
            <el-form-item label="标题:" prop="title">
              <el-input v-model="dataForm.title" placeholder="请输入供需标题" :disabled="judgeWrite('title')" :maxlength="20"
                clearable :style='{"width":"100%"}' show-word-limit>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="judgeShow('listintroduce')">
            <el-form-item label="简介:" prop="listintroduce">
              <el-input v-model="dataForm.listintroduce" placeholder="请输入简介" :disabled="judgeWrite('listintroduce')"
                :maxlength="50" clearable :style='{"width":"100%"}' show-word-limit>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="judgeShow('typeid')">
            <el-form-item label="供需分类:" prop="typeid">
              <el-select v-model="dataForm.typeid" placeholder="请选择" clearable :disabled="judgeWrite('typeid')"
                :style='{"width":"100%"}'>
                <el-option v-for="(item, index) in typeidOptions" :key="index" :label="item.name" :value="item.id"
                  :disabled="item.disabled" @focus="getAssoSupplyTypeListData"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="judgeShow('expiretime')">
            <el-form-item label="结束时间:" prop="expiretime">
              <el-date-picker v-model="dataForm.expiretime" :disabled="judgeWrite('expiretime')" placeholder="请选择日期时间"
                clearable :style='{"width":"100%"}' type="datetime" format="yyyy-MM-dd HH:mm:ss"
                value-format="timestamp">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="24" v-if="judgeShow('detaileddescribe')">
            <el-form-item label="详情描述:" prop="detaileddescribe">
              <JNPF-Quill v-model="dataForm.detaileddescribe" :disabled="judgeWrite('detaileddescribe')"
                placeholder="请输入">
              </JNPF-Quill>
            </el-form-item>
          </el-col>
          <el-col :span="24" v-if="judgeShow('filejson')">
            <el-form-item label="附件:" prop="filejson">
              <JNPF-UploadFz v-model="dataForm.filejson" :disabled="judgeWrite('filejson')" :fileSize="2"
                :showTip="true" sizeUnit="MB" :limit="1" buttonText="点击上传"></JNPF-UploadFz>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label-width="0">
              <JNPF-Text :style='{"width":"100%"}'
                :textStyle='{"color":"#000000","font-weight":"normal","text-decoration":"none","font-size":16,"line-height":16,"font-style":"normal","text-align":"left"}'
                value="联系信息" :closable="false">
              </JNPF-Text>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-divider content-position="center"></el-divider>
          </el-col>
          <el-col :span="12" v-if="judgeShow('contactname')">
            <el-form-item label="联系人:" prop="contactname">
              <el-input v-model="dataForm.contactname" :disabled="judgeWrite('contactname')" placeholder="请输入联系人"
                :maxlength="10" clearable :style='{"width":"100%"}' show-word-limit>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="judgeShow('contactphonenum')">
            <el-form-item label="联系电话:" prop="contactphonenum">
              <el-input v-model="dataForm.contactphonenum" :disabled="judgeWrite('contactphonenum')"
                placeholder="请输入联系电话" :maxlength="11" clearable :style='{"width":"100%"}'>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24" v-if="judgeShow('detailaddress')">
            <el-form-item label="详细地址:" prop="detailaddress">
              <el-input v-model="dataForm.detailaddress" :disabled="judgeWrite('detailaddress')" placeholder="请输入街道/门牌号"
                :maxlength="50" :style='{"width":"100%"}' true type="textarea" :autosize='{"minRows":4,"maxRows":4}'>
              </el-input>
            </el-form-item>
          </el-col>
        </template>
      </el-form>
    </el-row>
    <UserBox v-if="userBoxVisible" ref="userBox" @submit="submit" />
  </div>
</template>
<script>
  import {
    getAssoSupplyInfo,
    addAssoSupplyInfo,
    updateAssoSupplyInfo
  } from '@/api/asso/supply/list'
  import {
    getAssoSupplyTypeList
  } from '@/api/asso/supply/category'

  export default {
    name: 'vipsupplylistForm',
    components: {},
    props: [],
    data() {
      return {
        visible: false,
        loading: false,
        setting: {},
        eventType: '',
        userBoxVisible: false,
        currTableConf: {},
        addTableConf: {},
        tableRows: {},
        currVmodel: "",
        dataForm: {
          picture: [],
          title: '',
          listintroduce: '',
          typeid: "",
          expiretime: '',
          detaileddescribe: '',
          filejson: [],
          contactname: '',
          contactphonenum: '',
          detailaddress: '',
          supplydemandtype: 0
        },
        tableRequiredData: {},
        dataRule: {
          // picture: [{
          //   required: true,
          //   message: '请至少选择一个',
          //   trigger: 'change'
          // }, ],
          title: [{
            required: true,
            message: '请输入供需标题',
            trigger: 'blur'
          }, ],
          listintroduce: [{
            required: true,
            message: '请输入简介',
            trigger: 'blur'
          }, ],
          typeid: [{
            required: true,
            message: '请选择',
            trigger: 'change'
          }, ],
          expiretime: [{
            required: true,
            message: '请选择日期时间',
            trigger: 'change'
          }, ],
          contactname: [{
            required: true,
            message: '请输入联系人',
            trigger: 'blur'
          }, ],
          contactphonenum: [{
              required: true,
              message: '请输入联系电话',
              trigger: 'blur'
            },
            {
              pattern: /^1[3456789]\d{9}$|^0\d{2,3}-?\d{7,8}$/,
              message: '请输入正确的联系电话',
              trigger: 'blur'
            },
          ],
          detailaddress: [{
            required: true,
            message: '请输入街道/门牌号',
            trigger: 'blur'
          }, ],
        },
        typeidOptions: []
      }
    },
    computed: {
      formOperates() {
        return this.setting.formOperates
      }
    },
    watch: {},
    created() {},
    mounted() {},
    methods: {
      judgeShow(id) {
        if (!this.setting.formOperates || !this.setting.formOperates.length) return true
        let arr = this.setting.formOperates.filter(o => o.id === id) || []
        if (!arr.length) return true
        let item = arr[0]
        return item.read
      },
      judgeWrite(id) {
        if (!this.setting.formOperates || !this.setting.formOperates.length) return false
        let arr = this.setting.formOperates.filter(o => o.id === id) || []
        if (!arr.length) return true
        let item = arr[0]
        return !item.write
      },
      goBack() {
        this.$emit('refresh')
      },
      init(data) {
        this.dataForm.id = data.id || "";
        this.dataForm.supplydemandtype = data.supplydemandtype;
        this.setting = data;
        this.visible = true;
        this.updateDataRule()
        this.$nextTick(() => {
          this.$refs['elForm'].resetFields();
          if (this.dataForm.id) {
            this.loading = true
            getAssoSupplyInfo(this.dataForm.id).then((res) => {
              this.dataInfo(res.data)
              this.loading = false
            })
          }
          this.getAssoSupplyTypeListData()
          this.$emit('setPageLoad')
        })
        this.$store.commit('generator/UPDATE_RELATION_DATA', {})
      },
      getAssoSupplyTypeListData() {
        let _query = {
          superQueryJson: '',
          sort: "desc",
          sidx: "",
          showmark: '1'
        };
        getAssoSupplyTypeList(_query).then((res) => {
          this.typeidOptions = JSON.parse(JSON.stringify(res.data.list))
        })
      },
      updateDataRule() {
        let newRules = {}
        for (let i = 0; i < this.setting.formOperates.length; i++) {
          const item = this.setting.formOperates[i]
          if (!item.id.includes('-')) {
            const newRulesItem = {
              required: item.required,
              message: item.name + '不能为空',
              trigger: item.trigger || 'blur'
            }
            if (!this.dataRule.hasOwnProperty(item.id)) {
              if (item.required) this.$set(newRules, item.id, [newRulesItem])
            } else {
              let withoutRequiredItem = true
              for (let i = 0; i < this.dataRule[item.id].length; i++) {
                if (this.dataRule[item.id][i].hasOwnProperty('required')) {
                  // this.dataRule[item.id][i].required = item.required
                  withoutRequiredItem = false
                }
              }
              if (withoutRequiredItem && item.required) this.dataRule[item.id].push(newRulesItem)
            }
          } else {
            let key = item.id.split('-')[0]
            let newId = item.id.split('-')[1]
            let newItem = {
              ...item,
              id: newId
            }
            if (!this.tableRequiredData.hasOwnProperty(key)) {
              this.$set(this.tableRequiredData, key, [newItem])
            } else {
              this.tableRequiredData[key].push(newItem)
            }
          }
        }
        this.dataRule = {
          ...this.dataRule,
          ...newRules
        }
      },
      exist() {
        let isOk = true
        for (let key in this.tableRequiredData) {
          if (this.dataForm[key] && Array.isArray(this.dataForm[key])) {
            for (let i = 0; i < this.dataForm[key].length; i++) {
              let item = this.dataForm[key][i]
              inner: for (let id in item) {
                let arr = this.tableRequiredData[key].filter(o => o.id === id) || []
                if (!arr.length) continue inner
                if (arr[0].required) {
                  let msg = `${arr[0].name}不能为空`
                  let boo = true
                  if (arr[0].dataType === 'array') {
                    boo = !this.jnpf.isEmptyArray(item[id])
                  } else {
                    boo = !this.jnpf.isEmpty(item[id])
                  }
                  if (!boo) {
                    this.$message({
                      message: msg,
                      type: 'error',
                      duration: 1000
                    })
                    isOk = false
                    break
                  }
                }
              }
            }
          }
        }
        return isOk
      },
      judgeRequired(id) {
        if (!this.formOperates || !this.formOperates.length) return false
        let arr = this.formOperates.filter(o => o.id === id) || []
        if (!arr.length) return false
        let item = arr[0]
        return item.required
      },
      // 表单提交
      dataFormSubmit(eventType, flowUrgent) {
        // picture: [{
        //   message: '请至少选择一个',
        // }, ],
        // title: [{
        //   message: '请输入供需标题',
        // }, ],
        // listintroduce: [{
        //   message: '请输入简介',
        // }, ],
        // typeid: [{
        //   message: '请选择',
        // }, ],
        // expiretime: [{
        //   message: '请选择日期时间',
        // }, ],
        // contactname: [{
        //   message: '请输入联系人',
        // }, ],
        // contactphonenum: [{
        //     message: '请输入联系电话',
        //   },
        //     pattern: /^1[3456789]\d{9}$|^0\d{2,3}-?\d{7,8}$/,
        // ],
        // detailaddress: [{
        //   message: '请输入街道/门牌号',
        // }, ],
        // if(this.dataForm){

        //   return
        // }
        this.$refs['elForm'].validate((valid) => {
          if (valid) {
            if (this.exist && !this.exist()) return
            if (eventType === 'audit' || eventType === 'reject') {
              this.$emit('eventReceiver', this.dataForm, eventType)
              return
            }
            this.dataForm.status = eventType === 'submit' ? 0 : 1
            this.dataForm.flowId = this.setting.flowId
            this.dataForm.flowUrgent = flowUrgent
            this.eventType = eventType
            if (this.eventType === 'submit') {
              this.$confirm('您确定要提交当前流程吗, 是否继续?', '提示', {
                type: 'warning'
              }).then(() => {
                this.request()
              }).catch(() => {});
            } else {
              this.request()
            }
          }
        })
      },
      request() {
        var _data = this.dataList()
        if (!this.dataForm.id) {
          // 新增
          addAssoSupplyInfo(_data).then((res) => {
            this.$message({
              message: res.msg,
              type: 'success',
              duration: 1000,
              onClose: () => {
                this.visible = false
                this.$emit('close', true)
              }
            })
          })
        } else {
          // 修改
          updateAssoSupplyInfo(this.dataForm.id, _data).then((res) => {
            this.$message({
              message: res.msg,
              type: 'success',
              duration: 1000,
              onClose: () => {
                this.visible = false
                this.$emit('close', true)
              }
            })
          })
        }
      },
      openSelectDialog(key) {
        this.currTableConf = this.addTableConf[key]
        this.currVmodel = key
        this.selectDialogVisible = true
        this.$nextTick(() => {
          this.$refs.selectDialog.init()
        })
      },
      addForSelect(data) {
        for (let i = 0; i < data.length; i++) {
          let item = {
            ...this.tableRows[this.currVmodel],
            ...data[i]
          }
          this.dataForm[this.currVmodel].push(item)
        }
      },
      dataList() {
        var _data = JSON.parse(JSON.stringify(this.dataForm));
        _data.picture = _data.picture ? JSON.stringify(_data.picture) : []
        _data.filejson = JSON.stringify(_data.filejson)
        return _data;
      },
      dataInfo(dataAll) {
        let _dataAll = dataAll
        _dataAll.picture = _dataAll.picture ? JSON.parse(_dataAll.picture) : []
        _dataAll.filejson = JSON.parse(_dataAll.filejson)
        _dataAll.expiretime = new Date(_dataAll.expiretime)
        this.dataForm = _dataAll
      },
      uploadImgChange(e){
        // 上传成功后，手动验证一次表单
        this.$refs['elForm'].validateField('picture')
      },
    },
  }
</script>
<style lang="scss" scoped>
  ::v-deep .el-divider--horizontal {
    margin-top: 0;
  }

  .img_text {
    color: red;
  }
</style>
